<template>
  <div class="ai-summary">
    <div class="summary-header">
             <h3 class="summary-title">
         <el-icon class="title-icon"><MagicStick /></el-icon>
         AI 待办总结
       </h3>
      <el-dropdown @command="handleCommand" class="action-dropdown">
        <el-button type="primary" size="small">
          生成总结
          <el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="daily">
              <el-icon><Calendar /></el-icon>
              今日总结
            </el-dropdown-item>
                         <el-dropdown-item command="weekly">
               <el-icon><Calendar /></el-icon>
               本周总结
             </el-dropdown-item>
            <el-dropdown-item command="custom" divided>
              <el-icon><Setting /></el-icon>
              自定义范围
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="4" animated>
        <template #template>
          <el-skeleton-item variant="h3" style="width: 40%" />
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" style="width: 80%" />
        </template>
      </el-skeleton>
      <div class="loading-text">
        <el-icon class="rotating"><Loading /></el-icon>
        <div class="loading-messages">
          <p>AI正在分析您的待办事项，请稍候...</p>
          <p class="loading-tip">⏱️ AI处理通常需要30-90秒，请耐心等待</p>
        </div>
      </div>
    </div>

    <!-- 总结内容 -->
    <div v-else-if="summaryData" class="summary-content">
      <div class="summary-meta">
        <div class="meta-item">
          <el-icon><Calendar /></el-icon>
          <span>{{ getSummaryDateText() }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(summaryData.generatedAt) }}</span>
        </div>
        <div class="meta-item">
          <el-tag :type="getSummaryTypeColor()" size="small">
            {{ getSummaryTypeText() }}
          </el-tag>
        </div>
      </div>

      <div class="summary-text markdown-content" v-html="renderedSummary"></div>

            <div class="summary-actions">
        <el-button text type="primary" @click="copyToClipboard">
          <el-icon><CopyDocument /></el-icon>
          复制总结
        </el-button>
        <el-button text type="info" @click="regenerateSummary">
          <el-icon><Refresh /></el-icon>
          重新生成
        </el-button>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="还没有生成过总结" :image-size="80">
        <template #description>
          <p>点击上方按钮生成您的待办事项总结</p>
          <p>AI将分析您的任务完成情况并提供建议</p>
        </template>
      </el-empty>
    </div>

    <!-- 自定义日期范围对话框 -->
    <el-dialog
      v-model="showCustomDialog"
      title="自定义总结范围"
      width="400px"
    >
      <el-form :model="customForm" label-width="80px">
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="customForm.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="customForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCustomDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateCustomSummary"
          :loading="loading"
        >
          生成总结
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js' 
import 'highlight.js/styles/github.css'
import { 
  MagicStick, 
  ArrowDown, 
  Calendar, 
  Setting, 
  Clock, 
  Loading, 
  CopyDocument, 
  Refresh 
} from '@element-plus/icons-vue'
import { 
  generateDailySummary, 
  generateWeeklySummary, 
  generateCustomSummary as apiGenerateCustomSummary 
} from '../api/ai'
import { formatDate } from '../utils/date'

export default {
  name: 'AiSummary',
  components: {
    MagicStick,
    ArrowDown,
    Calendar,
    Setting,
    Clock,
    Loading,
    CopyDocument,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const summaryData = ref(null)
    const showCustomDialog = ref(false)
    const lastCommand = ref(null)
    
    const customForm = reactive({
      startDate: '',
      endDate: ''
    })

    // 配置marked选项
    marked.setOptions({
      breaks: true,
      gfm: true,
      highlight: function(code, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(code, { language: lang }).value
          } catch (err) {
            console.error('代码高亮失败:', err)
          }
        }
        return hljs.highlightAuto(code).value
      }
    })

    // 计算属性：渲染markdown内容
    const renderedSummary = computed(() => {
      if (!summaryData.value?.summary) return ''
      try {
        return marked.parse(summaryData.value.summary)
      } catch (error) {
        console.error('Markdown渲染失败:', error)
        return summaryData.value.summary
      }
    })

    const handleCommand = (command) => {
      lastCommand.value = command
      
      switch (command) {
        case 'daily':
          generateDaily()
          break
        case 'weekly':
          generateWeekly()
          break
        case 'custom':
          showCustomDialog.value = true
          break
      }
    }

    const generateDaily = async () => {
      try {
        loading.value = true
        const response = await generateDailySummary()
        
        if (response.data.code === 200) {
          summaryData.value = response.data.data
          ElMessage.success('当日总结生成成功')
        } else {
          ElMessage.error(response.data.message || '生成失败')
        }
      } catch (error) {
        console.error('生成当日总结失败:', error)
        ElMessage.error('生成失败，请检查网络连接或AI配置')
      } finally {
        loading.value = false
      }
    }

    const generateWeekly = async () => {
      try {
        loading.value = true
        const response = await generateWeeklySummary()
        
        if (response.data.code === 200) {
          summaryData.value = response.data.data
          ElMessage.success('本周总结生成成功')
        } else {
          ElMessage.error(response.data.message || '生成失败')
        }
      } catch (error) {
        console.error('生成本周总结失败:', error)
        ElMessage.error('生成失败，请检查网络连接或AI配置')
      } finally {
        loading.value = false
      }
    }

    const generateCustomSummary = async () => {
      if (!customForm.startDate || !customForm.endDate) {
        ElMessage.warning('请选择日期范围')
        return
      }

      if (new Date(customForm.startDate) > new Date(customForm.endDate)) {
        ElMessage.warning('开始日期不能晚于结束日期')
        return
      }

      try {
        loading.value = true
        showCustomDialog.value = false
        
        const response = await apiGenerateCustomSummary(
          customForm.startDate, 
          customForm.endDate
        )
        
        if (response.data.code === 200) {
          summaryData.value = response.data.data
          ElMessage.success('自定义范围总结生成成功')
        } else {
          ElMessage.error(response.data.message || '生成失败')
        }
      } catch (error) {
        console.error('生成自定义总结失败:', error)
        ElMessage.error('生成失败，请检查网络连接或AI配置')
      } finally {
        loading.value = false
      }
    }

    const regenerateSummary = () => {
      if (lastCommand.value) {
        handleCommand(lastCommand.value)
      } else {
        ElMessage.info('请先选择总结类型')
      }
    }

    const copyToClipboard = async () => {
      if (!summaryData.value?.summary) return

      try {
        await navigator.clipboard.writeText(summaryData.value.summary)
        ElMessage.success('总结已复制到剪贴板')
      } catch (error) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = summaryData.value.summary
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        ElMessage.success('总结已复制到剪贴板')
      }
    }

    const getSummaryDateText = () => {
      if (!summaryData.value) return ''
      
      const { type, date, startDate, endDate } = summaryData.value
      
      switch (type) {
        case 'daily':
          return `${formatDate(date)} (今日)`
        case 'weekly':
          return `${formatDate(startDate)} ~ ${formatDate(endDate)} (本周)`
        case 'custom':
          return `${formatDate(startDate)} ~ ${formatDate(endDate)} (自定义)`
        default:
          return ''
      }
    }

    const getSummaryTypeText = () => {
      if (!summaryData.value) return ''
      
      switch (summaryData.value.type) {
        case 'daily': return '今日总结'
        case 'weekly': return '本周总结'
        case 'custom': return '自定义总结'
        default: return ''
      }
    }

    const getSummaryTypeColor = () => {
      if (!summaryData.value) return 'info'
      
      switch (summaryData.value.type) {
        case 'daily': return 'primary'
        case 'weekly': return 'success'
        case 'custom': return 'warning'
        default: return 'info'
      }
    }

    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    return {
      loading,
      summaryData,
      showCustomDialog,
      customForm,
      renderedSummary,
      handleCommand,
      generateCustomSummary,
      regenerateSummary,
      copyToClipboard,
      getSummaryDateText,
      getSummaryTypeText,
      getSummaryTypeColor,
      formatTime
    }
  }
}
</script>

<style scoped>
.ai-summary {
  background: var(--el-bg-color);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 16px;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.summary-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.title-icon {
  font-size: 18px;
  color: var(--el-color-primary);
}

.loading-container {
  padding: 20px 0;
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-top: 16px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.loading-messages {
  text-align: center;
}

.loading-messages p {
  margin: 4px 0;
}

.loading-tip {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

.rotating {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.summary-content {
  padding: 16px 0;
}

.summary-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.summary-text {
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
  background: var(--el-fill-color-extra-light);
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

/* Markdown内容样式 */
.markdown-content {
  white-space: normal;
}

.markdown-content h1, 
.markdown-content h2, 
.markdown-content h3, 
.markdown-content h4, 
.markdown-content h5, 
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content h1 { font-size: 1.5em; color: var(--el-color-primary); }
.markdown-content h2 { font-size: 1.3em; color: var(--el-color-primary); }
.markdown-content h3 { font-size: 1.15em; color: var(--el-text-color-primary); }
.markdown-content h4 { font-size: 1em; color: var(--el-text-color-primary); }

.markdown-content p {
  margin: 8px 0;
  line-height: 1.6;
}

.markdown-content ul, 
.markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
  line-height: 1.5;
}

.markdown-content blockquote {
  margin: 8px 0;
  padding: 8px 12px;
  border-left: 4px solid var(--el-color-primary);
  background: var(--el-fill-color-lighter);
  color: var(--el-text-color-regular);
}

.markdown-content code {
  padding: 2px 4px;
  background: var(--el-fill-color);
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
}

.markdown-content pre {
  margin: 8px 0;
  padding: 12px;
  background: var(--el-fill-color);
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.markdown-content pre code {
  padding: 0;
  background: transparent;
  border-radius: 0;
}

.markdown-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 8px 0;
}

.markdown-content th,
.markdown-content td {
  padding: 8px 12px;
  border: 1px solid var(--el-border-color);
  text-align: left;
}

.markdown-content th {
  background: var(--el-fill-color-light);
  font-weight: 600;
}

.markdown-content strong {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.markdown-content em {
  font-style: italic;
  color: var(--el-text-color-regular);
}

.markdown-content hr {
  margin: 16px 0;
  border: none;
  border-top: 1px solid var(--el-border-color);
}

.markdown-content a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.summary-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.action-dropdown {
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .summary-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .summary-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .summary-actions {
    flex-direction: column;
  }
}
</style> 